import { defineStore } from "pinia";
import { reqlogintoken, reqUserInfo } from "../api/wcj-login/index";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
export const getLoginStore = defineStore("LoginStore", () => {
  let nickName = ref<any>("");
  let token = ref<any>("");
  let router = useRouter();
  let route = useRoute()
  
  const degnlu1 = async (data: any) => {
    try {
      let result: any = await reqlogintoken(data);

      if (result.code === 200) {

        token.value = result.data.token;
        localStorage.setItem("token", result.data.token);
        // let redirect:any = route.query.redirect
        console.log(route);
      
      
        
        // router.push(redirect||'/home')
      } else {
        ElMessage({
          type: "error",
          message: "账号或密码错误",
        });
      }
      return result.code
    } catch (error:any) {
      return Promise.reject(new Error(error.message));
    }
  };
  const reggetuser = async () => {
    let result: any = await reqUserInfo();
    if (result.code == 200) {
     
      nickName.value = result.data.nickName;
      console.log(nickName.value);
    } else {
      router.push('/login')
    }
  };
  const removetoken = () => {
    nickName.value = "";
    try {
      localStorage.removeItem("token");  
      return 'ok'
    } catch (error:any) {
      return Promise.reject(new Error(error.message));
    }
   
   
  };
  return {
    degnlu1,
    reggetuser,
    removetoken,
    nickName,
    token,
  };
});
